package com.nulstudio.sppm.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtils {
    /**
     * Token expires in 7 days.
     */
    private static final long EXPIRE_TIME = 7 * 24 * 3600 * 1000;

    /**
     * jwt 密钥
     */
    private static final String SECRET = "jwt_secret";

    public static String sign(String userId,String authority) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return  JWT.create()
                    // 将 userId 保存到 token 里面
                    .withClaim("UserId",userId)
                    .withClaim("Authority",userId)
                    .withExpiresAt(date)
                    // token 的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getUserId(String token) {
        try {
            return JWT.decode(token).getClaim("UserId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getUserAuthority(String token) {
        try {
            return JWT.decode(token).getClaim("Authority").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static void checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
        } catch (JWTVerificationException exception) {
            throw new RuntimeException("token 无效，请重新获取");
        }
    }
}
